package com.example.glkotlin

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Message
import android.view.View
import android.widget.Button
import android.widget.EditText
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.glkotlin.adapter.MsgAdapter
import com.example.glkotlin.bean.MsgBean
import java.util.ArrayList
import java.util.Objects

class MessageActivity : AppCompatActivity() {
    private var messageList = ArrayList<MsgBean>()
    private var isRec = false
    private var adapter: MsgAdapter? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_message)
        initMsg()
        adapter = MsgAdapter(messageList)
        val messageListview = findViewById<RecyclerView>(R.id.message_listview)
        messageListview.let {
            it.adapter = adapter
            it.layoutManager = LinearLayoutManager(this)
        }
        val messageInput = findViewById<EditText>(R.id.message_input)
        val messageSendBtn = findViewById<Button>(R.id.message_send_btn)
        messageSendBtn.setOnClickListener {
            if (isRec) {
                messageList.add(MsgBean(MsgBean.TYPE_RECEIVED, messageInput.text.toString()))
            } else {
                messageList.add(MsgBean(MsgBean.TYPE_SEND, messageInput.text.toString()))
            }
            isRec = !isRec
            adapter?.notifyItemChanged(messageList.size - 1)
            messageListview.scrollToPosition(messageList.size - 1)
        }
    }

    private fun initMsg() {
        val msg1 = MsgBean(MsgBean.TYPE_RECEIVED, "Hello guy.")
        messageList.add(msg1)
        val msg2 = MsgBean(MsgBean.TYPE_SEND, "Hello. Who is that?")
        messageList.add(msg2)
        val msg3 = MsgBean(MsgBean.TYPE_RECEIVED, "This is Tom. Nice talking to you. ")
        messageList.add(msg3)
    }
}